package com.LeeCode;

import java.util.HashMap;

/**
 * 最大好子数组和
 */

public class Code3026 {
    public static void main(String[] args) {
        int[] nums = {1, 5};
        int k = 2;
        System.out.println(new Code3026().maximumSubarraySum(nums, k));
    }

    public long maximumSubarraySum(int[] nums, int k) {
        int n = nums.length;
        long ans = Long.MIN_VALUE;
        long[] preSum = new long[n + 1];
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            // 检查第一个解
            int target = k + nums[i];
            if (map.containsKey(target)) {
                int index = map.get(target);
                ans = Math.max(ans, preSum[i] - preSum[index] + nums[i]);
            }
            // 检查第二个解
            target = -k + nums[i];
            if (map.containsKey(target)) {
                int index = map.get(target);
                ans = Math.max(ans, preSum[i] - preSum[index] + nums[i]);
            }

            // 计算前缀和
            preSum[i + 1] = preSum[i] + nums[i];

            // 更新最优候选点
            if (map.containsKey(nums[i])) {
                int index = map.get(nums[i]);
                if (preSum[i] - preSum[index] < 0)
                    map.put(nums[i], i);
            } else {
                map.put(nums[i], i);
            }
        }
        return ans == Long.MIN_VALUE ? 0 : ans;
    }
}
